package com.ykq.dao;

import com.ykq.entity.Book;
import com.ykq.entity.User;

import java.util.ArrayList;
import java.util.List;

public class BookDao extends BaseDao{

    /**
     * 查询所有图书
     * @return
     */
    public List<Book> selectAll(){
        List<Book> list = new ArrayList<Book>();
        try {
            String sql = "select * from tbl_book";
            getConn();
            ps=conn.prepareStatement(sql);
            rs=ps.executeQuery();
            while(rs.next()){
                //从数据库中获取指定列的值
                Book book=new Book();
                book.setId(rs.getInt("id"));
                book.setName(rs.getString("name"));
                book.setPrice(rs.getDouble("price"));
                book.setPublisher(rs.getString("publisher"));
                list.add(book);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeAll();
        }
        return list;
    }

    //删除方法
    public int delete(int id){
        String sql="delete from tbl_book where id=?";
    	return edit(sql,id);
    }

    public int insert(String name, double price, String publisher) {
        String sql="insert into tbl_book(name,price,publisher) values(?,?,?)";
        return edit(sql,name,price,publisher);
    }

    public Book findById(int id) {
        Book book=null;
        try {
            String sql = "select * from tbl_book where id=?";
            getConn();
            ps=conn.prepareStatement(sql);
            ps.setObject(1,id);
            rs=ps.executeQuery();
            while(rs.next()){
                //从数据库中获取指定列的值
                book=new Book();
                book.setId(rs.getInt("id"));
                book.setName(rs.getString("name"));
                book.setPrice(rs.getDouble("price"));
                book.setPublisher(rs.getString("publisher"));

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeAll();
        }
        return book;
    }
}
